import { FormSchema } from '@/components/Form'
interface MyFormSchema extends FormSchema {
  template?: string
}
type SelectType = {
  label: string
  value: string | number
  template?: string
  valueValue?: string
  type?: string
  disabled?: boolean
  hint?: string
  placeholder?: string
  options?: SelectType[] | OptionT[]
}
type OptionT = {
  label: string
  value: boolean | number | string
}
type DomForTItem = {
  componentProps?: SelectType[]
  componentPropsStyle?: SelectType[]
  componentPropsProps?: SelectType[]
  componentPropsOptions?: SelectType[]
  formItemPropsStyle?: SelectType[]
}
type DomForT = {
  Input: DomForTItem
  Autocomplete?: DomForTItem
  Select?: DomForTItem
  TreeSelect?: DomForTItem
  DatePicker?: DomForTItem
  DatePickers?: DomForTItem
  Switch?: DomForTItem
  RadioGroup?: DomForTItem
  RadioButton?: DomForTItem
  Slider?: DomForTItem
  InputNumber?: DomForTItem
  Upload?: DomForTItem
}
const isHaveOption: OptionT[] = [
  {
    label: '有',
    value: true
  },
  {
    label: '无',
    value: false
  }
]
const yesOrNo: OptionT[] = [
  {
    label: '是',
    value: true
  },
  {
    label: '否',
    value: false
  }
]
const positionList: OptionT[] = [
  {
    label: '左侧',
    value: 'left'
  },
  {
    label: '居中',
    value: 'center'
  },
  {
    label: '右侧',
    value: 'right'
  }
]
// 'year' | 'years' |'month' | 'months' | 'date' | 'dates' | 'datetime' | 'week' | 'datetimerange' | 'daterange' | 'monthrange' | 'yearrange'
const datePickerTypeList: OptionT[] = [
  {
    label: '某一天',
    value: 'date'
  },
  {
    label: '时间日期',
    value: 'datetime'
  },

  {
    label: '某一周',
    value: 'week'
  },
  {
    label: '某一月',
    value: 'month'
  },

  {
    label: '某一年',
    value: 'year'
  }
]
const datePickersTypeList: OptionT[] = [
  {
    label: '好几天',
    value: 'dates'
  },
  {
    label: '一段时间',
    value: 'daterange'
  },
  {
    label: '一段时间日期',
    value: 'datetimerange'
  },
  {
    label: '好几个月',
    value: 'months'
  },
  {
    label: '好几月',
    value: 'monthrange'
  },
  {
    label: '好几个年',
    value: 'years'
  },
  {
    label: '好几年',
    value: 'yearrange'
  }
]
const sizeOption: OptionT[] = [
  {
    label: '小',
    value: 'small'
  },
  {
    label: '中',
    value: 'default'
  },
  {
    label: '大',
    value: 'large'
  }
]

const fieldForm: SelectType[] = [
  {
    label: '字段',
    type: 'input',
    value: 'field'
  },
  {
    label: '标题',
    type: 'input',
    value: 'label'
  }
]

/**form公共表单项 */
const publicFormItemArr: SelectType[] = [
  ...fieldForm,
  {
    label: '初始值',
    type: 'input',
    value: 'value'
  },
  {
    label: '是否隐藏',
    type: 'radio',
    value: 'remove',
    hint: '如果为true，会连同值一同删除，类似v-if'
  },
  {
    label: '样式隐藏',
    type: 'radio',
    value: 'hidden',
    hint: '如果为true，会连同值一同删除，类似v-show'
  }
]
type DefaultDomDomT = {
  inputDivider: SelectType
  placeholder: SelectType
  startPlaceholder: SelectType
  endPlaceholder: SelectType
  clearable: SelectType
  size: SelectType
  width: SelectType
  minWidth: SelectType
  maxWidth: SelectType
  FormItemDivider: SelectType
  marginRight: SelectType
  marginBottom: SelectType
  propsDivider: SelectType
  propsLabel: SelectType
  propsValue: SelectType
  propsKey: SelectType
  children: SelectType
  disabled: SelectType
  disabledB: SelectType
  nodeKey: SelectType
  showCheckbox: SelectType
  datePickerType: SelectType
  datePickersType: SelectType
  valueFormat: SelectType
  format: SelectType
  loading: SelectType
  label: SelectType
  value: SelectType
  min: SelectType
  max: SelectType
  step: SelectType
}
const defaultDom: DefaultDomDomT = {
  inputDivider: {
    label: '输入框配置',
    type: 'divider',
    value: '输入框配置',
    placeholder: 'divider的Label'
  },
  placeholder: {
    label: '占位文本',
    type: 'input',
    value: 'placeholder'
  },
  startPlaceholder: {
    label: '开始占位文本',
    type: 'input',
    value: 'startPlaceholder'
  },
  endPlaceholder: {
    label: '结束占位文本',
    type: 'input',
    value: 'endPlaceholder'
  },
  clearable: {
    label: '清除按钮',
    type: 'radio',
    value: 'clearable',
    options: isHaveOption
  },
  size: {
    label: '尺寸',
    type: 'radio',
    value: 'size',
    options: sizeOption
  },
  width: {
    label: '宽度',
    type: 'input',
    value: 'width',
    placeholder: '受最小宽度限制'
  },
  minWidth: {
    label: '最小宽度',
    type: 'input',
    value: 'minWidth',
    placeholder: '数值+单位,例如：100px'
  },
  maxWidth: {
    label: '最大宽度',
    type: 'input',
    value: 'maxWidth',
    placeholder: '数值+单位,例如：100px'
  },
  FormItemDivider: {
    label: 'FormItem配置',
    type: 'divider',
    value: 'FormItem配置',
    placeholder: 'divider的Label'
  },
  marginRight: {
    label: '距离右侧间距',
    type: 'input',
    value: 'marginRight',
    placeholder: '数值+单位,例如：100px'
  },
  marginBottom: {
    label: '距离底部间距',
    type: 'input',
    value: 'marginBottom',
    placeholder: '数值+单位,例如：100px'
  },
  propsDivider: {
    label: 'props配置',
    type: 'divider',
    value: 'props配置',
    placeholder: 'divider的Label'
  },
  propsLabel: {
    label: '选项展示名字',
    type: 'input',
    value: 'label'
  },
  propsValue: {
    label: '选项的值',
    type: 'input',
    value: 'value'
  },
  propsKey: {
    label: '选项的key',
    type: 'input',
    value: 'key'
  },
  children: {
    label: 'children名字',
    type: 'input',
    value: 'children'
  },
  disabled: {
    label: '根据*字段禁用',
    type: 'input',
    value: 'disabled'
  },
  disabledB: {
    label: '是否禁用',
    type: 'radio',
    value: 'disabled',
    options: yesOrNo
  },
  nodeKey: {
    label: 'nodeKey',
    type: 'input',
    value: 'nodeKey'
  },
  showCheckbox: {
    label: '选择框',
    type: 'radio',
    value: 'showCheckbox',
    options: isHaveOption
  },
  datePickerType: {
    label: '类型',
    type: 'select',
    value: 'type',
    options: datePickerTypeList
  },
  datePickersType: {
    label: '类型',
    type: 'select',
    value: 'type',
    options: datePickersTypeList
  },
  valueFormat: {
    label: '值的格式',
    type: 'input',
    value: 'valueFormat'
  },
  format: {
    label: '显示的格式',
    type: 'input',
    value: 'format'
  },
  loading: {
    label: '是否显示加载中',
    type: 'radio',
    value: 'loading',
    options: yesOrNo
  },
  label: {
    label: '显示的文字',
    type: 'input',
    value: 'label'
  },
  value: {
    label: '对应的值',
    type: 'input',
    value: 'value'
  },
  min: {
    label: '最小值',
    type: 'inputNumber',
    value: 'min'
  },
  max: {
    label: '最大值',
    type: 'inputNumber',
    value: 'max'
  },
  step: {
    label: '步长',
    type: 'inputNumber',
    value: 'step',
    hint: '非负数。'
  }
}

const defaultStyle = { minWidth: '', maxWidth: '', width: '' }
const defaultProps = { label: 'label', value: 'value', key: 'id', children: 'children' }
const defaultValue = {
  clearable: true,
  size: 'default',
  style: defaultStyle
}
// 默认值配置
const propsDefault = {
  formItemPropsStyle: {
    marginRight: '32px',
    marginBottom: '18px'
  },
  Input: {
    placeholder: '请输入',
    ...defaultValue,
    props: defaultProps
  },
  Autocomplete: {
    placeholder: '请输入',
    debounce: 300,
    ...defaultValue,
    props: defaultProps
  },
  Select: {
    placeholder: '请选择',
    ...defaultValue,
    props: defaultProps
  },
  TreeSelect: {
    placeholder: '请选择',
    ...defaultValue,
    nodeKey: '',
    showCheckbox: false,
    props: { ...defaultProps, disabled: 'disabled' }
  },
  DatePicker: {
    placeholder: '请选择',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间',
    type: 'date',
    valueFormat: '',
    format: '',
    ...defaultValue
  },
  DatePickers: {
    placeholder: '请选择',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间',
    type: '',
    valueFormat: '',
    format: '',
    ...defaultValue
  },
  // 详情展示配置项，用于详情页的展示
  Detail: {
    field: '',
    label: '',
    span: 12,
    width: '',
    minWidth: '',
    align: 'left',
    labelAlign: 'left',
    className: '',
    labelClassName: ''
  },
  Table: {
    field: '',
    label: '',
    type: 'default',
    width: '',
    minWidth: '',
    fixed: false,
    align: 'left',
    headerAlign: 'left',
    className: '',
    labelClassName: ''
  },
  Switch: {
    width: '',
    disabled: false,
    loading: false,
    size: 'default',
    activeText: '',
    inactiveText: ''
  },
  RadioGroup: {
    disabled: false,
    size: 'default',
    textColor: '',
    fill: '',
    props: { ...defaultProps, disabled: 'disabled' },
    options: []
  },
  RadioButton: {
    disabled: false,
    size: 'default',
    textColor: '',
    fill: '',
    props: { ...defaultProps, disabled: 'disabled' },
    options: []
  },
  Slider: {
    disabled: false,
    size: 'default',
    min: 0,
    max: 100,
    step: 1,
    precision: 0,
    showInput: false,
    showStops: false,
    showInputControls: true
  },
  InputNumber: { disabled: false, size: 'default', min: 0, max: 100, step: 1 },
  Upload: {
    action: '',
    method: 'post',
    multiple: false,
    name: 'file',
    accept: ''
  }
}
// 核心转换函数
function convertToJSX(code) {
  // 基础正则表达式
  const regex = /_createVNode\("([^"]+)",\s*([^,]+),\s*\[([^\]]+)\]\)/

  // 增强版正则表达式（处理更多场景）
  const advancedRegex =
    /_createVNode\("([^"]+)",\s*(\{[^}]*\}|null|undefined),\s*\[?([\s\S]*?)\]?\)/g

  // 使用增强版正则进行替换
  const converted = code.replace(advancedRegex, (match, tag, props, children) => {
    console.log('match', match)

    // 处理子元素 - 去除多余的方括号
    const cleanChildren = children.trim()
    // console.log('cleanChildren', cleanChildren)
    // if (cleanChildren.startsWith('[') && cleanChildren.endsWith(']')) {
    //   cleanChildren = cleanChildren.substring(1, cleanChildren.length - 1)
    // }

    // 处理属性
    let propsString = ''
    if (props && props !== 'null' && props !== 'undefined') {
      try {
        const propsObj = new Function(`return ${props}`)()
        propsString = Object.entries(propsObj)
          .map(([key, value]) => {
            if (typeof value === 'string') {
              return `${key}="${value}"`
            } else {
              return `${key}={${value}}`
            }
          })
          .join(' ')
      } catch (e) {
        console.error('属性解析错误:', e)
      }
    }

    // 返回 JSX 格式
    return `<${tag}${propsString ? ' ' + propsString : ''}>${cleanChildren}</${tag}>`
  })

  return converted
}
// 自定义序列化函数
function customStringify(obj, space = 2) {
  const seen = new WeakSet()

  function replacer(key, value) {
    // 处理函数 - 转换为字符串
    if (typeof value === 'function') {
      // return value.toString()
      console.log('value', key, value)
      return convertToJSX(value.toString())
    }

    // 处理循环引用
    if (typeof value === 'object' && value !== null) {
      if (seen.has(value)) {
        return '[Circular Reference]'
      }
      seen.add(value)
    }

    return value
  }

  return JSON.stringify(obj, replacer, space)
}
// 将字符串转换为可执行函数
function parseFunction(str) {
  return new Function('return ' + str)()
}

//
/**
 * 删除对象中等于默认值的部分，递归比对两个对象中的值，并删除值相同的字段，并返回最终结果。
 *
 * @param defaultObj 默认值的对象
 * @param valObj 待处理的对象
 * @returns 处理后的对象
 */
function delDefaultVal(
  defaultObj: Record<string, any>,
  valObj: Record<string, any>
): Record<string, any> {
  const result = { ...valObj }
  for (const key in defaultObj) {
    if (!(key in result)) continue

    if (typeof defaultObj[key] !== 'boolean' && defaultObj[key] === result[key]) {
      delete result[key]
    } else if (isObject(defaultObj[key]) && isObject(result[key])) {
      const nestedResult = delDefaultVal(defaultObj[key], result[key])
      if (isEmptyObject(nestedResult)) {
        delete result[key]
      } else {
        result[key] = nestedResult
      }
    }
  }
  return result
}
/**
 * @abstract 判断一个值是否为对象
 * @param value 对象值
 */
function isObject(value) {
  return Object.prototype.toString.call(value) === '[object Object]'
}

/**
 * @abstract 判断一个对象是否为空对象
 * @param obj 对象
 */
function isEmptyObject(obj) {
  return Object.keys(obj).length === 0
}
import SetupFormOptionCode from './src/SetupFormOptionCode.vue'

export {
  SetupFormOptionCode,
  fieldForm,
  yesOrNo,
  isHaveOption,
  SelectType,
  OptionT,
  DomForT,
  defaultDom,
  propsDefault,
  positionList,
  MyFormSchema,
  convertToJSX,
  customStringify,
  parseFunction,
  isObject,
  isEmptyObject,
  delDefaultVal
}
